'use strict';
const BaseController = require('./base');
const { addRules, queryRules, deleteRules } = require('../validator/questtionAnswer/index');
class QuesttionAnswer extends BaseController {

  // 新增题目问答
  async add() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(addRules, ctx.request.body);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const data = ctx.request.body;
    const res = await service.questtionAnswer.add(data);
    ctx.helper.success({ bean: res }, '新增问答成功');
  }

  // 查询
  async query() {
    const { ctx, service, app } = this;
    let answers = await app.redis.get('answers')
    answers = JSON.parse(answers);
    if (answers && answers.length > 0) {
      ctx.helper.success({ beans: answers }, '查询问答成功');
    }

    const res = await service.questtionAnswer.query();
    if (res && res.length > 0) {
      await app.redis.set('answers', JSON.stringify(res), 'EX', 60 * 60);
    }
    ctx.helper.success({ beans: res }, '查询问答成功');
  }

  // 删除话题
  async delete() {
    const { ctx, service, app } = this;
    const errors = app.validator.validate(deleteRules, ctx.request.body);
    errors && ctx.helper.commonErr('参数错误', { beans: errors });
    const { id } = ctx.request.body;
    const res = await service.questtionAnswer.delete(id, ctx.helper.time());
    ctx.helper.success({ bean: res }, '删除问答成功');
  }
}

module.exports = QuesttionAnswer;
